package com.sczmgk.hotline_pzh.mainhomeUiView;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.adapter.MainHomeAdapter;
import com.sczmgk.hotline_pzh.adapter.MyNewsHomeAdapter;
import com.sczmgk.hotline_pzh.base.MainHomeBaseView;
import com.sczmgk.hotline_pzh.callback.CrashExceptionCallback;
import com.sczmgk.hotline_pzh.callback.HttpFailCallback;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.NewMsgCountDaoImpl;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.dialog.MessageDialog;
import com.sczmgk.hotline_pzh.entity.BannerInfo;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.ComplainInfo;
import com.sczmgk.hotline_pzh.entity.InformationBean;
import com.sczmgk.hotline_pzh.entity.MainHomeComplain;
import com.sczmgk.hotline_pzh.entity.MainHomeInfo;
import com.sczmgk.hotline_pzh.entity.MainHomeInformation;
import com.sczmgk.hotline_pzh.entity.ModuleInfo;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.jpush.MainHomeDataObserver;
import com.sczmgk.hotline_pzh.jpush.UIObserver;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.ui.BannerDetailActivity;
import com.sczmgk.hotline_pzh.ui.ChangeURL;
import com.sczmgk.hotline_pzh.ui.ChatActivity;
import com.sczmgk.hotline_pzh.ui.LoginActivity;
import com.sczmgk.hotline_pzh.ui.NewsDetailActivity;
import com.sczmgk.hotline_pzh.ui.NewsHomeActivity;
import com.sczmgk.hotline_pzh.ui.OnlineComplaintsActivity;
import com.sczmgk.hotline_pzh.utils.LogFile;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.utils.UIUtils;
import com.sczmgk.hotline_pzh.view.MyGridView;
import com.sczmgk.hotline_pzh.view.MyNewsListView;
import com.sczmgk.hotline_pzh.view.NoDoubleItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;

import static com.sczmgk.hotline_pzh.MyApp.bitmapUtils;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_CANCEL;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_EVALUTED;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_PRETREATMENTED;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_PRETREATMENT_FAIL;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_PROCESSING;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_CHECK;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_EVALUTE;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_PRETREATMENT;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_PROCESS;
import static com.sczmgk.hotline_pzh.ui.MainActivity.REQUEST_CODE_LOGIN;

/**
 * Created by Administrator on 2016/2/26.
 */
public class MainHomeApplication extends MainHomeBaseView{

    private Button changeURL;
    private Button refreshData;
    private Button mException;
    private final int REFRESH_POINT = 101;
    public static final int REREQUEST_MAINHOME_DATA = 102;
    public static final int NEWS_BACK_DATA = 103;
    public static String TAG_NEW_MSG_POINT = "tag_new_msg_point";
    public static final String MODULE_INFORMATION = "01";
    public static final String MODULE_CHAT = "02";
    public static final String MODULE_COMPLAIN = "03";
    private static final int MAIN_HOME_FUNCTION = 1;
    private static final int MAIN_HOME_BANNER = 2;
    private static final int MAIN_HOME_NEWS = 3;
    private static final int MAIN_HOME_COMPLAINT_INFO = 4;

    RadioButton mComplaintSettingRb;
    RadioButton mMe;

    private ViewPager mViewPagerBanner;
    private MyGridView mGvMainFunction;
    private ImageView mIvCompalaintSettingIcon;
    private TextView mTvCompalaintUpdateDate;
    private ImageView mIvCompalaintSettingImage;
    private TextView mTvCompalaintSettingState;
    private TextView mTvCompalaintSettingTitle;
    private TextView mTvCompalaintSettingdate;
    private LinearLayout mLComplaintSettingItem;
    private TextView mTvCompalaintSettingSearchMore;

    private View view;
    private MyNewsListView mLvMainNewsItem;
    private TextView mTvCompalaintSettingDes;

    private List<BannerInfo> bannerInfos;
    private List<ModuleInfo> functionInfos;

    private MyBannerAdapter bannerAdapter;
    private MainHomeAdapter functionAdapter;

    private MyNewsHomeAdapter listViewAdapter;
    private LinearLayout mLayoutPoint;
    private ImageView mIvSelectPoint;
    private ScrollView svMainHome;
    private List<ComplainInfo> complains = new ArrayList<>();
    private List<InformationBean> informations = new ArrayList<>();
    private MainHomeInformation information;
    private MainHomeComplain complain;
    private ScrollView mNetWorkFail;

    private MyHandler myHandler = null;
    private final BitmapUtils bannerBitmap;
    private MainHomeInfo mainHomeInfo;

    private MessageDialog messageDialog = DialogFactory.chooseDialog(activity, activity.getResources().getString(R.string.dialog_login_show),
            activity.getResources().getString(R.string.sure), activity.getResources().getString(R.string.cancel), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(activity, LoginActivity.class);
                    activity.startActivityForResult(intent, REQUEST_CODE_LOGIN);
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });

    public MainHomeApplication(Activity context, RadioButton mComplaintSettingRb, RadioButton mMe) {
        super(context);
        this.mComplaintSettingRb = mComplaintSettingRb;
        this.mMe = mMe;

        MainHomeDataObserver.getInstance().addObserver(this);
        bannerBitmap = new BitmapUtils(activity);
        bannerBitmap.configDefaultLoadFailedImage(R.drawable.banner2x);
        bannerBitmap.configDefaultBitmapMaxSize(400, 400);

        initView();

        // TODO 测试
//        initComplaintSettingItemView();
        //测试end
        initData();

        setListener();

    }

    private void setListener() {

        mLvMainNewsItem.setOnItemClickListener(new MyNewsItemClickListener());

        mGvMainFunction.setOnItemClickListener(new NoDoubleItemClickListener() {

            @Override
            public void NoDoubleItemClickListener(AdapterView<?> parent, View view, int i, long id) {
                switch (functionInfos.get(i).code) {
                    case MODULE_INFORMATION:
                        UIUtils.startActivity(activity, NewsHomeActivity.class);
                        break;
                    case MODULE_CHAT:
                        isNeedLogin(ChatActivity.class, 0);
                        break;
                    case MODULE_COMPLAIN:
                        isNeedLogin(OnlineComplaintsActivity.class, Constants.ONLINE_COMPLAINT_REQUEST_CODE);
                        break;
                }
            }
        });

        //TODO 测试加入
//        mIvCompalaintSettingIcon.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(activity, LoginActivity.class);
//                activity.startActivityForResult(intent, MainActivity.REQUEST_CODE_LOGIN);
//            }
//        });
        //切换url
        changeURL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UIUtils.startActivity(activity, ChangeURL.class);
            }
        });
        //刷新数据
        refreshData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initMainHomeData();
            }
        });

        mException.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String,Object> exceptionMaps = new HashMap<String,Object>();
                exceptionMaps.put("exceptiontype", 1);
                exceptionMaps.put("exceptioncontent", "测试异常日志上传");
                MyHttp.requestByUploadAppException(Constants.BASE_URL+ Constants.POST_UPLOAD_EXCEPTIOIN_LOG, exceptionMaps, MyHttp.POST, activity, new CrashExceptionCallback() {

                    @Override
                    public void onCrashExceptionCallback() {
//					MyLog.d(TAG,"请求回调 了,调用自杀.  mHandler = "+mHandler);//不能调用自杀？？？
//				    Message msg = Message.obtain();
//				    msg.what = 1;
//				    mHandler.sendMessage(msg);
//					android.os.Process.killProcess(android.os.Process.myPid());

                    }
                });
            }
        });
        //测试加入完
    }

    /**
     * 判断是否需要登录
     *
     * @param clazz
     */
    private void isNeedLogin(final Class<?> clazz, int request_code) {

        boolean isLogin = CacheUtils.getBooleanData(activity, Constants.IS_LOGIN_KEY, false);
        if (isLogin) {
//            UIUtils.startActivity(activity, clazz);
            Intent intent = new Intent(activity, clazz);
            activity.startActivityForResult(intent, request_code);
        } else {
            if (messageDialog != null && !messageDialog.isShowing()) {
                messageDialog.show();
            }
        }
    }

    @Override
    public void mHandleMessage(Message msg) {

        MyLog.i("mHandlerMessage", "mHandlerMessage");
        switch (msg.what) {

            case MAIN_HOME_FUNCTION:

                //功能的Adapter
                functionAdapter.setList(functionInfos);
                functionAdapter.notifyDataSetChanged();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshPoint();
                    }
                }, 500);

                break;

            case MAIN_HOME_BANNER:

                //banner的Adapter
                //TODO 测试时注掉
                mViewPagerBanner.setAdapter(bannerAdapter);

                //TODO 测试时加入
//                bannerAdapter.notifyDataSetChanged();


                setViewPagerBanner();

                break;

            case MAIN_HOME_NEWS:

                //资讯
                listViewAdapter.notifyDataSetChanged();

                //设置listView的头
                mLvMainNewsItem.setTitleText(R.string.title_latest_news);
                mLvMainNewsItem.setNewsIcon(R.drawable.zxzc2x);

//                for (int i = 0; i < informations.size(); i++) {
                    mLvMainNewsItem.setNewsDate(information.lasttime);
//                }

                break;

            case MAIN_HOME_COMPLAINT_INFO:

                initComplaintSettingItemView();

                break;
            case REFRESH_POINT:
                refreshPoint();

                break;

            case REREQUEST_MAINHOME_DATA:
//                initMainHomeData();
                MyLog.d(TAG, "登录成功---->,重新拉取数据");
//                break;
//            case NEWS_BACK_DATA :
                //点击新闻详情返回后重新拉取数据

            case Constants.LOGIN_OUT_CHANGE_DATA:

                //登录退出后重新拉取数据
//                initMainHomeData();
            break;
        }

    }


    /**
     * 刷新消息红点
     */
    private void refreshPoint() {

        int count = NewMsgCountDaoImpl.getIntance(activity).getCount();//TODO   android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed.
        TextView mPoint = (TextView) mGvMainFunction.findViewWithTag(TAG_NEW_MSG_POINT);
        if (mPoint != null) {

            if (count > 0) {
                mPoint.setVisibility(View.VISIBLE);
                mPoint.setText(count + "");
            } else {
                mPoint.setVisibility(View.GONE);
            }
        }

        if(isRefresh){
            mHandler.sendEmptyMessage(MAIN_HOME_COMPLAINT_INFO);
            mHandler.sendEmptyMessage(MAIN_HOME_NEWS);
            isRefresh = false;
        }
    }

    /**
     * 设置banner
     */
    private void setViewPagerBanner() {

        if (bannerInfos.size() > 0) {
            mIvSelectPoint.setVisibility(View.VISIBLE);
        } else {
            mIvSelectPoint.setVisibility(View.GONE);
            return;
        }

        mLayoutPoint.removeAllViews();

        //设置ViewPager的中心点
        for (int i = 0; i < bannerInfos.size(); i++) {
            // 添加灰点
            ImageView point = new ImageView(activity);
            point.setBackgroundResource(R.drawable.viewpager_point_normal);
            // 设置宽高
            int dp2px = Tools.dip2px(activity, 10);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dp2px, dp2px);
            point.setLayoutParams(params);
            // 让中间的点显示在屏幕中间
            if (i != 0) {
                params.leftMargin = dp2px;
            }
            mLayoutPoint.addView(point);
        }

        //处理轮播图
        processPlay();

        //设置点的移动
        mViewPagerBanner.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                int redPointX = (int) ((positionOffset + position) * Tools.dip2px(activity, 20));
                // 移动点，通过设置点的左边距，达到移动的效果
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mIvSelectPoint.getLayoutParams();
                // 设置左边距
                params.leftMargin = redPointX;
                mIvSelectPoint.setLayoutParams(params);
            }
        });
    }

    /**
     * 初始化布局
     */
    @Override
    public void initView() {

        // 初始化控件
        view = View.inflate(activity, R.layout.main_home_main_home_application, null);
        //更换URL
        changeURL = (Button) view.findViewById(R.id.bt_change_url);
        refreshData = (Button) view.findViewById(R.id.bt_refresh);
        mException = (Button) view.findViewById(R.id.bt_exception);
        mViewPagerBanner = (ViewPager) view.findViewById(R.id.vp_main_home_banner);//banner
        mGvMainFunction = (MyGridView) view.findViewById(R.id.gv_main_function);//功能栏

        //投诉处理的条目
        mLComplaintSettingItem = (LinearLayout) view.findViewById(R.id.ll_main_complaint_setting_item);

        //下方listView条目
        mLvMainNewsItem = (MyNewsListView) view.findViewById(R.id.lv_main_home_news_item);
        //ViewPager的中点
        mLayoutPoint = (LinearLayout) view.findViewById(R.id.ll_main_home_points);
        mIvSelectPoint = (ImageView) view.findViewById(R.id.iv_main_home_point);

        //网络布局控件
        mNetWorkFail = (ScrollView) view.findViewById(R.id.sv_net_work_fail);
        svMainHome = (ScrollView) view.findViewById(R.id.sv_main_home);

        //设置新闻时间的显示
        mLvMainNewsItem.setLoadMoreVisiable(false);

        mLvMainNewsItem.setFocusable(false);

        container.addView(view);
    }

    /**
     * 初始化投诉处理的控件
     */
    private void initComplaintSettingItemView() {

        boolean isLogin = CacheUtils.getBooleanData(activity, Constants.IS_LOGIN_KEY, false);
        if (complains == null || complains.size() == 0 || !isLogin){
            mLComplaintSettingItem.setVisibility(View.GONE);
            return;
        }

        //投诉处理的标题
        mIvCompalaintSettingIcon = (ImageView) view.findViewById(R.id.iv_main_complaint_setting_icon);
        mTvCompalaintSettingDes = (TextView) view.findViewById(R.id.tv_main_complaint_setting_des);
        mTvCompalaintUpdateDate = (TextView) view.findViewById(R.id.tv_main_complaint_update_date);
        mIvCompalaintSettingImage = (ImageView) view.findViewById(R.id.iv_main_complaint_setting_image);

        //投诉处理的描述
        mTvCompalaintSettingState = (TextView) view.findViewById(R.id.tv_main_complaint_setting_state);
        mTvCompalaintSettingTitle = (TextView) view.findViewById(R.id.tv_main_complaint_setting_title);
        mTvCompalaintSettingdate = (TextView) view.findViewById(R.id.tv_main_complaint_setting_date);

        //查看更多
        mTvCompalaintSettingSearchMore = (TextView) view.findViewById(R.id.tv_main_home_complaint_setting_search_more);
        View viewLayout = view.findViewById(R.id.complaint_setting_item_view);

        //查看更多的点击事件
        viewLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mComplaintSettingRb.setChecked(true);
            }
        });
        //TODO 测试时注掉的

        setComplaintItemData();

        //TODO 测试时加入的
//                mLComplaintSettingItem.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                UIUtils.startActivity(activity,ChatActivity.class);
//            }
//        });
    }

    /**
     * 设置投诉处理条目
     */
    public void setComplaintItemData() {
        //设置图片

        ComplainInfo complainInfo = complains.get(0);
        mLComplaintSettingItem.setVisibility(View.VISIBLE);


        if(complainInfo.picurls != null && complainInfo.picurls.size()>0){
            bitmapUtils.display(mIvCompalaintSettingImage, complainInfo.picurls.get(0).smallpic);
        }else{
            mIvCompalaintSettingImage.setImageResource(R.drawable.complain_default_pic) ;
        }

        //设置文本
        mTvCompalaintSettingDes.setText(activity.getResources().getString(R.string.main_home_complaint_setting));
        //设置最后的时间
        mTvCompalaintUpdateDate.setText(complain.lasttime);
        //设置图标
        mIvCompalaintSettingIcon.setImageResource(R.drawable.tscl2x);
        //设置查看更多
        mTvCompalaintSettingSearchMore.setText(R.string.search_more);
        mTvCompalaintSettingdate.setText(complainInfo.createtime);
        //设置投诉处理
        String titleState = getStatusStr(complainInfo.status);
        mTvCompalaintSettingState.setText(titleState);
        mTvCompalaintSettingTitle.setText(complainInfo.title);
    }

    private String getStatusStr(int status) {
        String statusStr = "未知";
        switch (status) {

            case STATUS_WAITING_PROCESS://用户提交
                statusStr = "待处理";
                break;
            case STATUS_WAITING_CHECK://后台分配给网格（可选）
                statusStr = "待审核";
                break;
            case STATUS_PROCESSING://网格通过，或不需要网格审核
                statusStr = "处理中";
                break;
            case STATUS_WAITING_EVALUTE://处理完成
                statusStr = "待评价";
                break;
            case STATUS_EVALUTED://评价完成
                statusStr = "已评价";
                break;
            case STATUS_CANCEL:
                statusStr = "已取消投诉";
                break;
            case STATUS_WAITING_PRETREATMENT://分配给网格
                statusStr = "待审核";
                break;
            case STATUS_PRETREATMENTED://网格通过
                statusStr = "处理中";
                break;
            case STATUS_PRETREATMENT_FAIL:
                statusStr = "审核失败";
                break;
        }
        return statusStr;
    }

    /**
     * 初始化数据
     */
    private void initData() {

        //初始化集合
        bannerInfos = new ArrayList<>(); //bannew的集合
        functionInfos = new ArrayList<>();//功能的集合

        //初始化adapter
        bannerAdapter = new MyBannerAdapter();
        functionAdapter = new MainHomeAdapter(functionInfos, R.layout.main_function_item, activity);
        listViewAdapter = new MyNewsHomeAdapter(activity);

        //TODO 测试时加入
//        mViewPagerBanner.setAdapter(bannerAdapter);
        //test end

        //设置功能的Adapter
        mGvMainFunction.setAdapter(functionAdapter);

        //设置listView的Adapter
        mLvMainNewsItem.setAdapter(listViewAdapter);

        initMainHomeData();
    }

    private void initMainHomeData() {

        if (bannerInfos.size() > 0) {
            mIvSelectPoint.setVisibility(View.VISIBLE);
        } else {
            mIvSelectPoint.setVisibility(View.GONE);
        }

        boolean isLogin = CacheUtils.getBooleanData(activity, Constants.IS_LOGIN_KEY, false);
        int userid;
        if (isLogin) {
            userid = CacheUtils.getIntData(activity, Constants.LOGIN_UID, 0);
        } else {
            userid = 0;
        }
        Map<String, Object> infos = new HashMap<>();

        infos.put("userid", userid);
        infos.put("imei", MyApp.imei);

        MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.GET_MAIN_HOME_DATA_URL, infos, MyHttp.GET, activity, true, null, new SimplePaserJsonCallback() {

            @Override
            public void onVerifyIsNull() {
                svMainHome.setVisibility(View.VISIBLE);
                mNetWorkFail.setVisibility(View.GONE);
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                Log.i("MainHomeApplication  :", dataRaw);
                svMainHome.setVisibility(View.VISIBLE);
                mNetWorkFail.setVisibility(View.GONE);
                try {
                    paserMainHomeDataJson(dataRaw, isCache);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    LogFile.writeLog(dataRaw, "mainhomedata.txt");
                    e.printStackTrace();
                }

            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                svMainHome.setVisibility(View.VISIBLE);
                mNetWorkFail.setVisibility(View.GONE);
            }
        }, new HttpFailCallback() {
            @Override
            public void onServiceErrorCallback() {
                if (mainHomeInfo == null) {
                    svMainHome.setVisibility(View.GONE);
                    mNetWorkFail.setVisibility(View.VISIBLE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            initMainHomeData();
                        }
                    }, 16000);
                }
            }
        });

    }

    private void paserMainHomeDataJson(String dataRaw, boolean isCache) {
        Gson gson = new Gson();
        mainHomeInfo = gson.fromJson(dataRaw, MainHomeInfo.class);
        List<BannerInfo> banners = mainHomeInfo.banners;
        List<ModuleInfo> modules = mainHomeInfo.modules;
        information = mainHomeInfo.information;
        complain = mainHomeInfo.complain;

        //1.设置banner
        if (bannerInfos.size() > 0) {
            bannerInfos.clear();
        }
        bannerInfos.addAll(banners);
        mHandler.sendEmptyMessage(MAIN_HOME_BANNER);

        //2.设置模块
        if (functionInfos.size() > 0) {
            functionInfos.clear();
        }
        functionInfos.addAll(modules);
        mHandler.sendEmptyMessage(MAIN_HOME_FUNCTION);
        //3.设置资讯


        if (listViewAdapter.getLists() != null && listViewAdapter.getLists().size() > 0) {
            listViewAdapter.getLists().clear();
        }
        informations.addAll(information.informations);
        if (informations != null) {
            listViewAdapter.setLists(informations);
            mHandler.sendEmptyMessage(MAIN_HOME_NEWS);
        }
        complains.clear();
        //4.设置我的投诉
        if (complain != null && complain.complains != null && complain.complains.size() > 0) {

            complains.add(complain.complains.get(0));
        }
        mHandler.sendEmptyMessage(MAIN_HOME_COMPLAINT_INFO);
    }

    /**
     * 处理无限轮播
     */
    private void processPlay() {

        // 发送延迟消息，切换轮播图
        if (myHandler == null) {
            myHandler = new MyHandler();
        }
        // 把前面发送的消息删除
        myHandler.removeCallbacksAndMessages(null);// null 删除所有的Callbacks 和Messages
        myHandler.sendMessageDelayed(Message.obtain(), 3000);

    }

    /**
     * Banner的ViewPagerAdapter
     */
    private class MyBannerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return bannerInfos == null ? 0 : bannerInfos.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View view = View.inflate(activity, R.layout.item_main_home_banner, null);

            ImageView imageView = (ImageView) view.findViewById(R.id.iv_main_home_banner_image);

            final BannerInfo lists = bannerInfos.get(position);

            if (lists.picurl != null && lists.picurl.length() > 0) {
                String picurl = lists.picurl;
                bannerBitmap.display(imageView, picurl);
            }else {
                imageView.setImageResource(R.drawable.banner2x);
            }

            container.addView(view);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(activity, BannerDetailActivity.class);
                    intent.putExtra(Constants.BANNER_DETAIL_INFO, lists.url);
                    activity.startActivity(intent);
                }
            });

            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 实现Banner的无限循环播放
     */
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            if (isResume && bannerInfos.size() > 0) {
                // 实现无限循环，再次发生消息
                myHandler.sendMessageDelayed(Message.obtain(), 3000);
                int item = (mViewPagerBanner.getCurrentItem() + 1) % bannerInfos.size();
//                MyLog.e(TAG,"pager  count: "+mViewPagerBanner.getChildCount()+  "          setposition: "+item);
                if (item == 0) {// 从最后一张到第一张时，不要动画效果
                    mViewPagerBanner.setCurrentItem(item, false);
                } else {
                    mViewPagerBanner.setCurrentItem(item);
                }
            }

        }
    }

    /**
     * 资讯ListView条目点击事件
     */
    private class MyNewsItemClickListener extends NoDoubleItemClickListener {

        @Override
        public void NoDoubleItemClickListener(AdapterView<?> parent, View view, int i, long id) {
            int position = i - 1;
            InformationBean informationBean = information.informations.get(position);
            //
//            String title = mLvMainNewsItem.getTitleText();//最新资讯
//            IndicatorInfos byQuery = InformationTitleDaoImpl.getIntance(activity).findByQuery(informationBean.type);
//            String title=null;
//            if(byQuery != null){
//                title = byQuery.title;
//            }
            Intent intent = new Intent(activity, NewsDetailActivity.class);
//            intent.putExtra(Constants.MORE_NEWS_TITLE,title);
            intent.putExtra(Constants.NEWS_DETAIL_ITEM, informationBean);

            activity.startActivity(intent);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshPoint();
        int count = mViewPagerBanner.getChildCount();
        int adaptercount = bannerAdapter.getCount();
        MyLog.e(TAG, "pageer count : " + count + "    banners count  ：" + bannerInfos.size() + "   adapterCount: " + adaptercount);
        //处理轮播
//        mViewPagerBanner.removeAllViews();
        processPlay();
    }

    private boolean isRefresh;
    @Override
    public void update(Observable observable, Object o) {

        if(observable.getClass().isInstance(UIObserver.getInstance())){
            MyLog.d(TAG,"update-------------刷新红点");
            mHandler.sendEmptyMessage(REFRESH_POINT);
            //1.找到聊天功能模块的item
            //2.设置红点
        }else{
            MyLog.e(TAG,"update-------------刷新主页数据");
            initMainHomeData();
            isRefresh = true;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        MyLog.e(TAG, "MainhomeApplication  onPause");

        myHandler.removeCallbacksAndMessages(null);// null 删除所有的Callbacks 和Messages
    }

}
